package other.edan.newpaas.bid;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.BidManagement__c;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.edan.newpaas.utils.ComUtils;
import other.edan.newpaas.utils.HCXObjectService;

import java.util.*;

/**
 * @Description 生成授权编号
 */
public class CreateBidManagetCode implements Trigger {

    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "新增投标管理: 生成授权编号 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        LOGGER.debug(LOGGER_MSG + "触发开始");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<XObject> objectList = new ArrayList<>();
        for (XObject xObject : dataList) {
            objectList.add(xObject);
            dataResultList.add(new DataResult(true, "", xObject));
        }

        BidManagement__c bidManagement = (BidManagement__c) objectList.get(0);
        generateCode(bidManagement);

        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    public static void main(String[] args) throws Exception {
        BidManagement__c bidManagement__c = new BidManagement__c();
        bidManagement__c.setId(3608762893507247L);
        bidManagement__c = HCXObjectService.get(bidManagement__c);
        new CreateBidManagetCode().generateCode(bidManagement__c);
    }

    /**
     * 生成授权编码  规则: 办事处编码 + 用途编码 + '-' + 人员编码 + 年份 + 月份 + 序号
     * @param bidManagement
     */
    public void generateCode(BidManagement__c bidManagement) {
        try {
            LOGGER.info(LOGGER_MSG + "开始处理");
            // 只针对业务类型（entityType）为 项目资料（3421587888429740）、备案资料（3440045102324381）
            Long entityType = bidManagement.getEntityType();
            Integer powerOfAttorney = bidManagement.getPowerOfAttorney__c();
            List<Long> entityTypeList = Arrays.asList(3421587888429740L, 3440045102324381L);
            if (!entityTypeList.contains(entityType) || Objects.equals(powerOfAttorney, 2)) {
                LOGGER.info(LOGGER_MSG + "只处理类型为项目资料、备案资料且授权书值不是 '无需'的数据");
                return;
            }

            // 获取【资料用途】 选项集
            JSONObject salesOrderDesc = ComUtils.getEntityDesc("bidManagement__c");
            Map<String, String> dataUsageOpt = ComUtils.getMapsFromDescribeJson(salesOrderDesc, "ziliaoYongtu__c", "value", "apiKey"); // 资料用途
            LOGGER.info(LOGGER_MSG + "dataUsageOpt:" + dataUsageOpt);

            // 获取人员编码、办事处编码 (获取 办事处助理 所属部门的办事处编码)
            String sql = "select id,name,applyUser__c,ziliaoYongtu__c,toubiaoZhuanyuan__c.bidGroupNo__c bidGroupNo__c,bscZhuli__c.residentOffice__c.officeCode__c officeCode__c " +
                    " from bidManagement__c where id = " + bidManagement.getId();
            JSONObject bidData = HCXObjectService.queryAllUseXoql(sql).get(0);
            LOGGER.info(LOGGER_MSG + "bidData: " + bidData);

            // 获取后缀编码 当前最新的投标管理
            String oriSuffixCode = "";
            String suffixCode = "";
            String officeCode = bidData.getString("officeCode__c"); // 办事处编码

            // 当前最新的投标管理
            if (StringUtils.isBlank(officeCode)) {
                officeCode = "XX";
                sql = String.format("select id,authorizationNo__c from bidManagement__c where entityType in (3421587888429740,3440045102324381) and powerOfAttorney__c != 2 and bscZhuli__c.residentOffice__c.officeCode__c is null and id != %s" +
                        " order by createdAt desc limit 1", bidManagement.getId());
            } else {
                sql = String.format("select id,authorizationNo__c from bidManagement__c where entityType in (3421587888429740,3440045102324381) and powerOfAttorney__c != 2 and bscZhuli__c.residentOffice__c.officeCode__c = '%s' and  id != %s" +
                        " order by createdAt desc limit 1", officeCode, bidManagement.getId());
            }
            List<JSONObject> bidArray = HCXObjectService.queryAllUseXoql(sql);
            if (bidArray.size() > 0) {
                // 新的编码或许序号
                String name = bidArray.get(0).getString("authorizationNo__c");
                // name = "XXGK-00240903";
                if (StringUtils.isNotBlank(name) && name.split("-").length > 1) {
                    oriSuffixCode = name;
                    String s = name.split("-")[1];
                    suffixCode = s.substring(2);
                }
            }
            LOGGER.info(LOGGER_MSG + "suffixCode: " + suffixCode);

            // 拼接授权编码 规则: 办事处编码 + 用途编码 + '-' + 人员编码 + 年份 + 月份 + 序号
            // 人员编码 （投标组成员编码）
            String personCode = bidData.getString("bidGroupNo__c");
            if (StringUtils.isBlank(personCode)) {
                personCode = "xx";
            }

            // 获取序号
            Date date = new Date();
            String yearMonths = String.format("%ty%tm", date, date); // 年月 2409
            LOGGER.info(LOGGER_MSG + "yearMonths: " + yearMonths);
            int number = 1;
            if (StringUtils.isNotBlank(suffixCode)) {
                // 有值 判断办事处、年月是否一致，一致则序号 + 1, 不一致序号则从01开始
                String oldYearMonths = suffixCode.substring(0, 4);
                String oldNumber = suffixCode.substring(4);
                String oldOfficeCode = oriSuffixCode.substring(0, 2); // 办事处编码
                if (Objects.equals(officeCode, oldOfficeCode) && Objects.equals(yearMonths, oldYearMonths)) {
                    number = Integer.valueOf(oldNumber) + 1;
                }
            }

            String purposeCode = dataUsageOpt.get(bidData.getString("ziliaoYongtu__c")); // 用途编码
            String authCode = String.format("%s-%s%02d", officeCode + purposeCode, personCode + yearMonths, number);
            LOGGER.info(LOGGER_MSG + "authCode: " + authCode);

            // 更新授权编码
            BidManagement__c upBidManagement = new BidManagement__c();
            upBidManagement.setId(bidManagement.getId());
            upBidManagement.setAuthorizationNo__c(authCode);
            OperateResult update = HCXObjectService.update(upBidManagement);
            LOGGER.info(LOGGER_MSG + "更新授权编码: " + update.getSuccess());

            LOGGER.info(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(LOGGER_MSG + "处理异常: " + e.getMessage());
        }
    }


}
